package com.jiuzhe.commercial.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.bean.UserBean;
import com.jiuzhe.commercial.constant.Constants;
import com.jiuzhe.commercial.http.CallBack;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.utils.SPUtil;
import com.jiuzhe.commercial.utils.UIUtils;

import java.util.HashMap;


/**
 * Created by huanghao on 2018/6/12.
 */

public class StartActivity extends Activity {
    private Handler handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        atuoLogin();
        handler = new Handler();
        handler.postDelayed(thread, 3000);
    }


    private void atuoLogin() {
        HashMap<String, String> map = new HashMap<>();
        String token = SPUtil.getString(StartActivity.this, Constants.TOKEN);
        final String id = SPUtil.getString(StartActivity.this, Constants.ID);
        if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(token)) {
            map.put("id", id);
            String autoSignStr = Constants.AUTOLOGIN.substring(Constants.AUTOLOGIN.lastIndexOf("0/") + 1) + "?token=";
            String signStr = UIUtils.Md5(autoSignStr + token);
            map.put("token", id);
            map.put("sign", signStr);
            HttpClient.post(this, Constants.AUTOLOGIN, map, new CallBack<UserBean>() {
                @Override
                public void onSuccess(UserBean result) {
                    if (id.equals(result.getId())) {
                        SPUtil.put(StartActivity.this, Constants.MERCHANTID, result.getUserDto().getMerchantId());
                        SPUtil.put(StartActivity.this, Constants.TOKEN, result.getTaken());
                        UIUtils.startActivity(MainActivity.class);
                       // finish();
                        SPUtil.put(StartActivity.this,"isLogin",true);
                    }
                }
            });
        }
    }

    private Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            boolean flag =   SPUtil.getBoolean(StartActivity.this, "isLogin");
            if (flag) {
                startActivity(new Intent(StartActivity.this, MainActivity.class));
            } else {
                startActivity(new Intent(StartActivity.this, LoginActivity.class));
            }
            finish();
        }
    });

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        handler.removeCallbacks(thread);
    }
}
